package com.ucpaas.paas.web.common.interceptor;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.Properties;

/**
 *
 * @author MaxWang
 * @create 2017-12-08 9:51
 * @modifyer taoj 2018-09-06 修改StopWatch设置查询时间
 **/
@Intercepts(value = {
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class})})
@Component
public class SqlTimeInterceptor implements Interceptor {
    private static final Logger LOG = LoggerFactory.getLogger(SqlTimeInterceptor.class);
    private static final String SQL_STOP_WATCH = "sql[ %s ] time";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        Object returnValue;
        StopWatch stopWatch = new StopWatch();
        stopWatch.start(String.format(SQL_STOP_WATCH, sqlId));
        returnValue = invocation.proceed();
        stopWatch.stop();
        LOG.debug(stopWatch.toString());
        return returnValue;
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
